const jwt = require('jsonwebtoken');
const User = require('@models/user');
const R = require('@common/r');

// 用户校验中间件，从请求头中authorization获取token，token是通过 Bearer 前缀
const authMiddleware = async (req, res, next) => {
  try {
    const { authorization } = req.headers;
    if (!authorization) return res.send(R.errMsg('当前用户未知，请正确姿势操作！'));
    const token = authorization.split(' ')[1];
    // 使用jwt验证token
    const { id } = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findOne({
      where: { id },
      attributes: { exclude: ['password'] }
    });
    if (!user) return res.send(R.errCode(2, '当前用户不存在，请重试！'))
    req.user = user;
    next();
  } catch (e) {
    res.send(R.errMsg(e.message))
  }
}

module.exports = {
  authMiddleware,
}